import { Button, Modal, Popconfirm, Space, Table } from "antd";
import React, { useEffect, useState } from "react";
import { useAppDispatch, useAppSelector } from "../../utils/store/hooks";
import {
  addCollectionType,
  delCollectionType,
  getCollectionType,
  updateCollectionType,
} from "../../utils/store/collectionTypeSlice";
import { CollectionTypeModal } from "./CollectionTypeModal";
import styles from "./CollectionType.module.css";
import { CollectionType as CollectionTypeDomain } from "../../utils/domain/CollectionType";
import { formatDate } from "../../utils/common/formatTime";
import { useNavigate } from "react-router-dom";
import { toast } from "../../components/Toast/Toast";

let behavior: "add" | "modify" = "add";

let chosenCollectionType: null | CollectionTypeDomain = null;

export const CollectionType = (props: {
  confirm: (rowData: CollectionTypeDomain) => void;
}) => {
  //   const dataSource: CollectionTypeDomain[] = [];
  const dataSource = useAppSelector((store) => store.collectionType);

  const columns = [
    // {
    //   title: "index",
    //   render: (row: any, record: any, index: number) => {
    //     return <div>{index + 1}</div>;
    //   },
    // },
    {
      title: "Name",
      dataIndex: "typeName",
      key: "typeName",
    },
    {
      title: "description",
      dataIndex: "description",
      key: "description",
      render: (row: string) => {
        return <div className={styles.textWrap}>{row}</div>;
      },
    },
    {
      title: "create time",
      dataIndex: "createTime",
      key: "createTime",
      render: (data: CollectionTypeDomain["createTime"]) => {
        return <div>{formatDate(data)}</div>;
      },
    },
    {
      title: "operation",
      fixed: "right" as const,
      render: (row: CollectionTypeDomain) => {
        return (
          <Space>
            <Button
              type="primary"
              onClick={() => {
                behavior = "modify";
                setShowModal({
                  show: true,
                  item: row,
                });
              }}
            >
              modify
            </Button>
            <Popconfirm
              title="Delete the collection type?"
              description="Are you sure to delete this item?"
              onConfirm={async () => {
                await dispatch(delCollectionType(row.id));
                refresh();
              }}
              okText="Yes"
              cancelText="No"
            >
              <Button danger>Delete</Button>
            </Popconfirm>
          </Space>
        );
      },
    },
  ];

  const defaultModalItem = () => ({
    id: -1,
    typeName: "",
    description: "",
    createTime: 0,
  });

  const [showModal, setShowModal] = useState<{
    show: boolean;
    item: CollectionTypeDomain;
  }>({
    show: false,
    item: defaultModalItem(),
  });
  const collectionType = useAppSelector((data) => data.collectionType);
  const dispatch = useAppDispatch();
  const to = useNavigate();

  const restoreDefaultItem = (show: boolean = false) =>
    setShowModal({ item: defaultModalItem(), show });

  const refresh = () => {
    dispatch(
      getCollectionType({
        pageNo: collectionType.pageNo,
        pageSize: collectionType.pageSize,
      })
    );
  };

  useEffect(() => {
    refresh();
  }, []);

  return (
    <div>
      {/* <Space className={styles.bottomGap}>
        <Button
          type="primary"
          onClick={() => {
            to(-1);
          }}
        >
          back
        </Button>
      </Space> */}
      <Space>
        <Button
          className={styles.addCollectionTypeBut}
          type="primary"
          onClick={() => ((behavior = "add"), restoreDefaultItem(true))}
        >
          add
        </Button>
        <Button
          type="primary"
          onClick={() => {
            if (chosenCollectionType) props.confirm(chosenCollectionType);
            else toast("please choose one type!");
          }}
        >
          confrim
        </Button>
      </Space>
      <Table
        scroll={{ x: 1000 }}
        pagination={{
          pageSize: collectionType.pageSize,
          onChange: (pageNo) => {
            dispatch(
              getCollectionType({
                pageNo,
                pageSize: collectionType.pageSize,
              })
            );
          },
        }}
        dataSource={dataSource.list}
        columns={columns}
        rowSelection={{
          type: "radio",
          onChange: (
            selectedRowKeys: React.Key[],
            selectedRows: CollectionTypeDomain[]
          ) => {
            chosenCollectionType = selectedRows[0];
            // console.log(
            //   `selectedRowKeys: ${selectedRowKeys}`,
            //   "selectedRows: ",
            //   selectedRows
            // );
          },
        }}
        rowKey={"id"}
      />

      <Modal
        open={showModal.show}
        footer={<></>}
        onCancel={() => restoreDefaultItem()}
      >
        <CollectionTypeModal
          data={showModal.item}
          onSubmit={async (data) => {
            if (behavior === "add") await dispatch(addCollectionType(data));
            else await dispatch(updateCollectionType(data));
            restoreDefaultItem();
            refresh();
          }}
        />
      </Modal>
    </div>
  );
};
